var pc = null;
var name = "webrtc" + new Date().getTime() + Math.floor(Math.random() * 10);
var socket;
var dataChannel;
var platform_code = ''

function onAnswer(data) {
    console.log("OnAnswer", data);
    pc.setRemoteDescription(new RTCSessionDescription(data.answer));
}

function initSocket() {
    socket = new WebSocket("wss://webrtc.wechain360.com/websocketRTC/" + name)
    socket.onopen = function () {
        console.log("Connected");
    };

    socket.onmessage = function (message) {
        var data = JSON.parse(message.data);

        switch (data.type) {
            case "answer":
                onAnswer(data);
                break;
            default:
                console.log("default message");
                console.log(data);
                break;
        }
    };

    socket.onerror = function (err) {
        console.log("socket error", err);
    };

    socket.onclose = function () {
        console.log("socket close");
    }
}

initSocket();

function negotiate() {
    pc.addTransceiver('video', { direction: 'recvonly' });
    pc.addTransceiver('audio', { direction: 'recvonly' });
    return pc.createOffer().then((offer) => {
        return pc.setLocalDescription(offer);
    }).then(() => {
        // wait for ICE gathering to complete
        return new Promise((resolve) => {
            if (pc.iceGatheringState === 'complete') {
                resolve();
            } else {
                const checkState = () => {
                    if (pc.iceGatheringState === 'complete') {
                        pc.removeEventListener('icegatheringstatechange', checkState);
                        resolve();
                    }
                };
                pc.addEventListener('icegatheringstatechange', checkState);
            }
        });
    }).then(() => {
        var offer = pc.localDescription;
        let message = {
            type: "offer",
            offer: offer,
            from: name,
            to: platform_code,
        };
        console.log("send offer: ", message)
        socket.send(JSON.stringify(message));
    }).catch((e) => {
        alert(e);
    });
}

function start() {
    console.log("start");
    document.getElementById('start').style.display = 'none'
    // 获取输入框的值
    platform_code = document.getElementById('platformInput').value;
    let config = {
        iceServers: [{
            "urls": ["turn:39.106.154.90:3478"],
            "username": "lipeng",
            "credential": "123456"
        }]
    };

    pc = new RTCPeerConnection(config);

    // connect audio / video
    pc.addEventListener('track', (evt) => {
        if (evt.track.kind == 'video') {
            document.getElementById('video').srcObject = evt.streams[0];
//        } else {
//            document.getElementById('audio').srcObject = evt.streams[0];
        }
    });
    dataChannel = pc.createDataChannel("chat");

    dataChannel.onopen = function(event) {
        console.log('Data Channel is open');
    };

    dataChannel.onmessage = function(event) {
        console.log('Received message:', event.data);
    };

    negotiate();
}

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return (false);
}

//document.getElementById('video').addEventListener('click', (event) => {
//    // 计算点击位置相对于视频的位置
//    const rect = event.target.getBoundingClientRect();
//    const x = event.clientX - rect.left;
//    const y = event.clientY - rect.top;
//
//    // 创建并发送鼠标事件消息
//    const message = {
//        type: "mouse_event",
//        event: "click",
//        position: {x: x/rect.width, y: y/rect.height},
//        button: "left"
//    };
//    console.log(message)
//    // socket.send(JSON.stringify(message));
//    if (dataChannel && dataChannel.readyState === 'open') {
//        dataChannel.send(JSON.stringify(message));
//    }
//});

document.getElementById('video').addEventListener('contextmenu', (event) => {
    event.preventDefault(); // 阻止默认的右键点击菜单
    // 计算点击位置
    const rect = event.target.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    // 创建并发送鼠标右键事件消息
    const message = {
        type: "mouse_event",
        event: "click",
        position: {x: x/rect.width, y: y/rect.height},
        button: "right"
    };
    console.log(message)
    // socket.send(JSON.stringify(message));
    if (dataChannel && dataChannel.readyState === 'open') {
        dataChannel.send(JSON.stringify(message));
    }
});

document.getElementById('video').addEventListener('keydown', (event) => {
    event.preventDefault();

    let key = event.key;
    let isCombination = false;

    if (event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) {
        isCombination = true;
        key = `${event.ctrlKey ? 'Ctrl+' : ''}${event.shiftKey ? 'Shift+' : ''}${event.altKey ? 'Alt+' : ''}${event.metaKey ? 'Meta+' : ''}${key}`;
    }

    const message = {
        type: "keyboard_event",
        event: "keydown",
        key: key,
        isCombination: isCombination
    };

    console.log(message);
    // socket.send(JSON.stringify(message));
    if (dataChannel && dataChannel.readyState === 'open') {
        dataChannel.send(JSON.stringify(message));
    }
});

let mouseDownPosition = null;
let mouseDownTime = 0;

document.getElementById('video').addEventListener('mousedown', (event) => {
    // 记录鼠标按下的位置
    mouseDownPosition = { x: event.clientX, y: event.clientY };
    mouseDownTime = Date.now()
});

document.getElementById('video').addEventListener('mouseup', (event) => {
    if (mouseDownPosition) {
        const dx = event.clientX - mouseDownPosition.x;
        const dy = event.clientY - mouseDownPosition.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        mouseUpPosition = { x: event.clientX, y: event.clientY };

        if (Date.now() - mouseDownTime > 300) {
            // 发送拖动结束的事件
            sendMousemoveEvent(event, mouseDownPosition);
        } else {
            // 计算点击位置相对于视频的位置
            const rect = event.target.getBoundingClientRect();
            const x = event.clientX - rect.left;
            const y = event.clientY - rect.top;

            // 创建并发送鼠标事件消息
            const message = {
                type: "mouse_event",
                event: "click",
                position: {x: x/rect.width, y: y/rect.height},
                button: "left"
            };
            console.log(message)
            // socket.send(JSON.stringify(message));
            if (dataChannel && dataChannel.readyState === 'open') {
                dataChannel.send(JSON.stringify(message));
            }
        }

        mouseDownPosition = null; // 重置鼠标按下的位置
    }
});

function sendMousemoveEvent(event, mouseDownPosition) {
    const rect = event.target.getBoundingClientRect();
    const x1 = (mouseDownPosition.x - rect.left) / rect.width;
    const y1 = (mouseDownPosition.y - rect.top) / rect.height;
    const x = (event.clientX - rect.left) / rect.width;
    const y = (event.clientY - rect.top) / rect.height;

    const message = {
        type: "mousemove_event",
        position: {x: x1, y: y1},
        positionUp: {x: x, y: y},
        button: "left"
    };
    console.log(message);

    if (dataChannel && dataChannel.readyState === 'open') {
        dataChannel.send(JSON.stringify(message));
    }
}